import { makeAutoObservable, toJS } from 'mobx'
import { getData, postData } from '@/servers/http'
import { api } from '@/servers/api'
import type { SliderValue } from 'antd-mobile/es/components/slider'
import type { RecordViewData } from './interface'
import { getLocalStorage } from '@/storage'

/** 讲师图片暂时不替换 */
const teacherCover: Record<string, string> = {
    '25': 'https://wtbl-img.oss-cn-hangzhou.aliyuncs.com/tarining/test-eval/icon_huolande%402x.png',
    '8': 'https://wtbl-img.oss-cn-hangzhou.aliyuncs.com/tarining/test-eval/icon_mbti%402x.png',
    '29': 'https://wtbl-img.oss-cn-hangzhou.aliyuncs.com/tarining/test-eval/icon_yaliceshi.png',
    '26': 'https://wtbl-img.oss-cn-hangzhou.aliyuncs.com/tarining/test-eval/icon_jiuyezhuanye%402x.png',
    '27': 'https://wtbl-img.oss-cn-hangzhou.aliyuncs.com/tarining/test-eval/icon_hexintongyong%402x.png',
    '28': 'https://wtbl-img.oss-cn-hangzhou.aliyuncs.com/tarining/test-eval/icon_fazhannengli%402x.png',
}

class Store {
    /** 关卡信息 */
    taskInfo: any = {}

    /** 测评记录 */
    recordList: any = []
    /** 接口请求中 */
    loading: boolean = true

    /** 能力测评模块 */
    moduleList: {
        barrier_id: string
        cover: string
        detail: string
        dimension_type: string
        id: string
        name: string
        tag: string
        type: string
        checked?: boolean
        userEvalPaper: null | object
        user_finish_status: string
    }[] = []

    /** 题目详情 */
    quesInfo: Record<
        string /** 模块id eval_id */,
        {
            barrier_id: string
            id: string
            name: string
            detail: string
            eval_explain: string
            questions: any[]
            userEvalPaper: null | object
        }
    > = {}

    /** 雷达图信息 */
    radarInfo: Record<
        string /** 模块id eval_id */,
        {
            name: string
            score: SliderValue
            question_id: string
        }[]
    > = {}

    /** 回答详情数据 */
    answerInfo: Record<
        string /** 模块id eval_id */,
        Record<
            string /** 题目id */,
            {
                question_id: string
                score: string
                name: string
                title: string
            }
        >
    > = {}

    /** 测评详情数据 */
    resultData?: RecordViewData = undefined

    constructor() {
        makeAutoObservable(this)
    }

    /** 获取关卡信息 */
    getTaskInfo = (id: string) => {
        return getData(`${api.userBarriersById}${id}`).then(res => {
            // console.log(res)
            this.taskInfo = res.data
            const { detail = [] } = res.data
            /** 如果有结果 生成 雷达图数据、 */
            detail?.forEach((item: any) => {
                if (!this.answerInfo[item.eval_id]) {
                    this.answerInfo[item.eval_id] = {}
                }
                const { userEvalPaperResult } = item
                const radarList = userEvalPaperResult.map((result: any) => {
                    const { question_id, score, evalQuestion, eval_id } = result
                    const { evalConfigQuestion, title } = evalQuestion
                    // console.log('evalConfigQuestion', evalConfigQuestion)
                    this.answerInfo[eval_id][question_id] = {
                        question_id,
                        score,
                        name: evalConfigQuestion?.config?.name,
                        title,
                    }
                    return {
                        score,
                        name: evalConfigQuestion?.config?.name,
                        question_id,
                    }
                })
                // this.radarInfo[item.eval_id] = radarList
            })
        })
    }

    /** 获取能力测评模块 */
    getTestEvalsList = async (id: string, focus?: boolean) => {
        if (this.moduleList.length > 0 && focus !== true) {
            return
        }
        getData(api.testEvals).then(res => {
            const identityType = getLocalStorage('IDENTITY_TYPE')
            this.moduleList = Number(identityType) !== 2 ? res.data : res.data.map((item: any) => ({ ...item, cover: teacherCover[item.id] }))
        })
        // await this.getTaskInfo(id)
    }

    /** 获取相应测评能力题目 */
    getQuestionInfo = (barrier_id: string, eval_id: string) => {
        if (this.quesInfo[eval_id]) {
            return
        }
        getData(`${api.testEvals}/${barrier_id}`, { eval_id }).then(res => {
            this.quesInfo[eval_id] = res.data
            this.quesInfo[eval_id] = {
                ...res.data,
                questions: res.data.questions.map((item: any) => {
                    const answerInfo = this.answerInfo[eval_id] || {}
                    // console.log(toJS(answerInfo), answerInfo?.[item.id])
                    return {
                        ...item,
                        value: answerInfo?.[item.id]?.score,
                    }
                }),
            }
        })
    }

    /** 保存答案 */
    setAnswer = (evalId: string, idx: number, val: SliderValue) => {
        this.quesInfo[evalId].questions[idx].value = val
    }

    /** 测评结果保存 */
    saveRadar = (evalId: string) => {
        const { questions, barrier_id, id: eval_id, userEvalPaper } = this.quesInfo[evalId]
        // this.radarInfo[evalId] = questions.map(item => ({
        //     name: item.evalConfigQuestion.config.name,
        //     score: item.value || 0,
        //     question_id: item.id,
        //     id: item.evalConfigQuestion.config.id,
        // }))

        /** 设置列表已完成 */
        // this.moduleList.forEach(item => {
        //     if (item.id === evalId) {
        //         item.checked = true
        //     }
        // })

        /** 编辑保存 */
        // if (userEvalPaper) {
        this.handleSave(
            barrier_id,
            eval_id,
            questions.map(item => ({ id: item.id, score: item.value || 0 })),
        )
        // }

        // console.log(toJS(this.radarInfo))
    }

    /** 保存测评模块 */
    handleSave = (id: string, eval_id: string, questions: { id: string; score: string }[]) => {
        return postData(api.testEvalsSave, { barrier_id: id, eval_id, questions })
    }

    /** 提交能力测评 */
    handleFinish = () => {
        // const questionIdList = Object.keys(this.quesInfo)
        return getData(`${api.userBarriersIsFinish}${this.taskInfo.id}`).then(
            (res): Promise<any> => {
                const { is_finish } = res.data
                if (is_finish === '1') {
                    return Promise.resolve(true)
                } else {
                    return postData(`${api.userBarriersBatchInput}${this.taskInfo.id}`)
                }
            },
        )

        // return Promise.all(
        //     questionIdList
        //         .map((id: string) => {
        //             const { barrier_id, id: eval_id, questions, userEvalPaper } = this.quesInfo[id]
        //             /** 过滤已经提交的模块 */
        //             if (userEvalPaper) {
        //                 return true
        //             }
        //             return this.handleSave(
        //                 barrier_id,
        //                 eval_id,
        //                 questions.map(item => ({ id: item.id, score: item.value || 0 })),
        //             )
        //         })
        //         .filter(item => item !== true),
        // ).then((data): Promise<any> => {
        //     /** 判断是否有提交模块、已经提交的不会重复提交 */
        //     if (Array.isArray(data) && data?.length === 0) {
        //         return Promise.resolve(true)
        //     }
        //     /** 关卡提交获取金币 */
        //     return postData(`${api.userBarriersBatchInput}${this.taskInfo.id}`)
        // })
    }

    /** 获取能力测评结果 */

    /** 重新测评 */
    handleReset = () => {
        this.moduleList = []
        this.quesInfo = {}
        this.radarInfo = {}
    }

    /** 获取测评结果记录 */
    getTestEvalsRecordList = () => {
        getData(api.testEvalsRecordList)
            .then(res => {
                this.recordList = res.data
            })
            .finally(() => {
                this.loading = false
            })
    }

    /** 获取测评结果详情 */
    getTestEvalsRecordView = (id: string) => {
        getData(`${api.testEvalsRecordView}/${id}`).then(res => {
            this.resultData = res.data
            const { userEvalPaperResult } = res.data
            this.radarInfo = userEvalPaperResult.map((result: any) => {
                const { question_id, score, evalQuestion } = result
                const { evalConfigQuestion } = evalQuestion

                return {
                    score,
                    name: evalConfigQuestion?.config?.name,
                    question_id,
                }
            })
        })
    }
}

const jobAbility = new Store()
export default jobAbility
